import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:merchants/models/app_config.dart';
import 'package:merchants/models/review.dart';
import 'package:merchants/models/spu.dart';
import 'package:merchants/enum/spu_status.dart';

class SpuService {
  static Future<String> _getBaseUrl() async {
    return await AppConfig.getFullBaseUrl();
  }

  static Future<List<Spu>> getList({String? status}) async {
    try {
      final baseUrl = await _getBaseUrl();
      final uri = Uri.parse(
        '$baseUrl/spu/get-list',
      ).replace(queryParameters: status != null ? {'status': status} : null);
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({}),
      );

      if (response.statusCode == 200) {
        // 解析 JSON 响应
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        // 提取 data.records 字段
        final List<dynamic> records =
            responseData['data']['records'] as List<dynamic>;
        // 将 records 映射为 Spu 列表
        return records
            .map((json) => Spu.fromJson(json as Map<String, dynamic>))
            .toList();
      } else {
        throw Exception(
          'Failed to load SPUs: ${response.statusCode} - ${response.body}',
        );
      }
    } catch (e) {
      throw Exception('Error fetching SPUs: $e');
    }
  }

  static Future<void> updateSpu(Spu spu) async {
    try {
      final baseUrl = await _getBaseUrl();
      final response = await http.put(
        Uri.parse('$baseUrl/spus/${spu.id}'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(spu.toJson()),
      );
      if (response.statusCode != 200) {
        throw Exception(
          'Failed to update SPU: ${response.statusCode} - ${response.body}',
        );
      }
    } catch (e) {
      throw Exception('Error updating SPU: $e');
    }
  }

  static Future<List<Review>> fetchReviews() async {
    try {
      final baseUrl = await _getBaseUrl();
      final response = await http.get(Uri.parse('$baseUrl/comments'));
      if (response.statusCode == 200) {
        final List<dynamic> data = jsonDecode(response.body);
        return data
            .map((json) => Review.fromJson(json as Map<String, dynamic>))
            .toList();
      } else {
        throw Exception(
          'Failed to load reviews: ${response.statusCode} - ${response.body}',
        );
      }
    } catch (e) {
      throw Exception('Error fetching reviews: $e');
    }
  }

  static Future<String> createSpu(Spu spu) async {
    try {
      final baseUrl = await _getBaseUrl();
      final response = await http.post(
        Uri.parse('$baseUrl/spu/create'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'data': spu.toJson()}),
      );
      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        return responseData['data']['id'];
      } else {
        throw Exception(
          'Failed to create SPU: ${response.statusCode} - ${response.body}',
        );
      }
    } catch (e) {
      throw Exception('Error creating SPU: $e');
    }
  }

  static Future<void> deleteSpu(String id) async {
    try {
      final baseUrl = await _getBaseUrl();
      final response = await http.delete(Uri.parse('$baseUrl/spus/$id'));
      if (response.statusCode != 200) {
        throw Exception(
          'Failed to delete SPU: ${response.statusCode} - ${response.body}',
        );
      }
    } catch (e) {
      throw Exception('Error deleting SPU: $e');
    }
  }

  static Future<String> createSpuWithImages({
    required String name,
    required String category,
    required String description,
    required SpuStatus status,
    required List<Map<String, dynamic>> skus,
    required List<File> images,
  }) async {
    final baseUrl = await _getBaseUrl();
    var request = http.MultipartRequest(
      'POST',
      Uri.parse('$baseUrl/spu/create'),
    );

    // 添加表单数据
    request.fields['name'] = name;
    request.fields['category'] = category;
    request.fields['description'] = description;
    request.fields['status'] = status.toString().split('.').last;
    request.fields['skus'] = jsonEncode(skus);

    // 添加图片文件
    for (var image in images) {
      request.files.add(
        await http.MultipartFile.fromPath('images', image.path),
      );
    }

    // 发送请求
    final response = await request.send();
    final responseData = await http.Response.fromStream(response);

    if (response.statusCode == 200) {
      final data = jsonDecode(responseData.body);
      return data['id'] ?? 'success'; // 返回 SPU ID 或成功标志，视后端返回而定
    } else {
      throw Exception('提交失败: ${response.statusCode} - ${responseData.body}');
    }
  }
}
